import React, { Component } from 'react'
import root from '../..'

/* export default class Demo extends Component {
    state = { count: 0 }
    myRef = React.createRef()

    componentDidMount() {
        this.timer = setInterval(() => {
            const { count } = this.state
            this.setState({ count: count + 1 })
        }, 1000)
    }

    componentWillUnmount() {
        clearInterval(this.timer)
    }

    add = () => {
        this.setState({ count: this.state.count + 1 })
    }

    unmount = () => {
        root.unmount()
    }

    show = () => {
        alert(this.myRef.current.value)
    }

    render() {
        return (
            <div>
                <input type="text" ref={this.myRef} />
                <h2>当前求和是：{this.state.count}</h2>
                <button onClick={this.add}>count+1</button>
                <button onClick={this.unmount}>卸载组件</button>
                <button onClick={this.show}>点我提示输入框内容</button>
            </div>
        )
    }
} */

export default function Demo() {
    // 函数式组件也可以使用State，State hook
    const [count, setCount] = React.useState(0)

    const myRef = React.useRef()

    // React.useEffect 模拟生命周期钩子
    // 最后一个参数空数组，表示什么状态也不监测，只在组件初始化时调用函数  此时相当于componentDidMount
    // 不加空数组这个参数，表示什么都监测，任何改变都能调用函数
    React.useEffect(() => {
        let timer = setInterval(() => {
            setCount(count => count + 1)
        }, 1000);
        return () => {
            // 相当于componentwillUnmount
            clearInterval(timer)
        }
    }, [])

    function add() {
        // setCount(count+1) 第一种写法
        setCount(count => count + 1)
    }

    function unmount() {
        root.unmount()
    }

    function show() {
        alert(myRef.current.value)
    }

    return <div>
        <h2>当前求和是：{count}</h2>
        <input type="text" ref={myRef} />
        <button onClick={add}>count+1</button>
        <button onClick={unmount}>卸载组件</button>
        <button onClick={show}>点我提示输入框内容</button>
    </div>
}
